package com.example.demofdfs.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import net.neoremind.sshxcute.core.Result;

public class JSchDemo {
	   private String charset = "UTF-8"; // 设置编码格式
	    private String user; // 用户名
	    private String passwd; // 登录密码
	    private String host; // 主机IP
	    private JSch jsch;
	    private Session session;
	    private Channel channel;
	    /**
	     *
	     * @param user用户名
	     * @param passwd密码
	     * @param host主机IP
	     */
	    public JSchDemo(String user, String passwd, String host) {
	        this.user = user;
	        this.passwd = passwd;
	        this.host = host;
	    }

	    /**
	     * 连接到指定的IP
	     *
	     * @throws JSchException
	     */
	    public void connect() throws JSchException {
	        jsch = new JSch();
	        session = jsch.getSession(user, host, 22);
	        session.setPassword(passwd);
	        java.util.Properties config = new java.util.Properties();
	        config.put("StrictHostKeyChecking", "no");
	        session.setConfig(config);
	        session.connect();
	    }
	    
	    public Session getSession(String host) {
	    	Session session = null;
	    	try {
				session = jsch.getSession(user, host);
				session.sendKeepAliveMsg();
			} catch (JSchException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return session;
	    }

	    /**
	     * 执行相关的命令
	     */
	    public synchronized Result execCmd(String cmd) {
//	        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

	        //String command = "ls ;rm -f aa.log; ls ";
	        //String command = "tar -czf aa.tar.gz aa.log";
	        //String command = "tar -zxvf aa.tar.gz";
	        //String command = "tar -zxvf aa.tar.gz";
	        //String command = "/root/test.sh";
	        //String command = "reboot";
	        //String command = "echo abc >> xx.txt";
	        String command = cmd;

	        //String command = "echo \"always\" >/sys/kernel/mm/transparent_hugepage/enabled ";
	        Result result = new Result();
	        try {
	            channel = session.openChannel("exec");
	            ((ChannelExec) channel).setCommand(command);
	            channel.setInputStream(null);
//	            channel.setOutputStream(null);
	            ByteArrayOutputStream baos = new ByteArrayOutputStream();
	            ((ChannelExec) channel).setErrStream(baos);

	            InputStream in = channel.getInputStream();
	            channel.connect();
	            
	            byte[] b = new byte[1024];
	            int len;
	            StringBuilder sb = new StringBuilder("");
	            while (true) {
		            while (in.available() > 0) {
		            	if ((len = in.read(b)) < 0)
		            		break;
		            	sb.append(new String(b, 0, len, "UTF-8"));
		            }
		            if (channel.isClosed()) {
		            	if ((result.rc = channel.getExitStatus()) != 0) {
		            		result.error_msg = new String(baos.toByteArray());
		            	} else {
		            		result.sysout = sb.toString();
		            	}
		            }
		            break;
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        } catch (JSchException e) {
	            e.printStackTrace();
	        } finally {
	            channel.disconnect();
//	            session.disconnect();
	        }
			return result;
	    }

	    public static void main(String[] args) throws Exception {
	        String user = "root";
	        String passwd = "root";
	        String host = "192.168.225.133";
	        JSchDemo demo = new JSchDemo(user, passwd, host);
	        long startTime = System.currentTimeMillis();
	        demo.connect();
	        System.out.println("   " + (System.currentTimeMillis() - startTime) / 1000);
	        
//	        demo.getSession(host);
	        
	        demo.execCmd("ls -al ");
	        demo.execCmd("sss ");
	        demo.execCmd("sss ");
	        demo.execCmd("sss ");
	        demo.execCmd("sss ");
	        
//	        for (int i = 0; i < 10; i++) {
//	        	final int ii = i;
//				new Thread(()-> demo.execCmd("sss " + ii)).start();
//	        }
	    }
}
